<?php

/**
 * @author      Nguyen Duc Thuan <me@ndthuan.com>
 * @copyright   Copyright (c) 2009 Nguyen Duc Thuan <me@ndthuan.com>
 */
class Fete_View_Helper_HeadScript extends Fete_View_Helper
{
    protected $_scripts     = '';
    protected $_scriptTag   = 'SCRIPT';

    public function &headScript($src = null, $type = 'text/javascript'
        , $extras = array())
    {
        if (null !== $src) {
            $this->appendFile($src, $type, $extras);
        }

        return $this;
    }

    public function &appendFile($src, $type = 'text/javascript'
        , $extras = array())
    {
        $this->_scripts .= $this->_genHtml($src, $type, $extras);

        return $this;
    }

    public function &prependFile($src, $type = 'text/javascript'
        , $extras = array())
    {
        $this->_scripts = $this->_genHtml($src, $type, $extras) . $this->_scripts;

        return $this;
    }

    protected function _genHtml($src, $type = 'text/javasript'
        , $extras = array())
    {
        $script = '<' . $this->_scriptTag
        . ' type="' . $type . '" src="' . $src . '"';

        foreach ($extras as $attrib => $value)
        {
            $script .= ' ' . $attrib . '="' . $value . '"';
        }

        $script .= '></' . $this->_scriptTag . '>';

        return $script;
    }

    public function __construct()
    {
        if ('XHTML' === substr($this->docType()->getDocType(), 0, 5)) {
            $this->_scriptTag = 'script';
        }
    }

    public function __toString()
    {
        return $this->_scripts;
    }
}